import 'package:craze/common/index.dart';
import 'package:craze/models/index.dart';
import 'package:craze/services/index.dart';
import 'package:craze/stores/index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:video_player/video_player.dart';

class VideoView extends StatefulWidget {
  const VideoView({super.key});

  @override
  State<VideoView> createState() => _VideoViewState();
}

class _VideoViewState extends State<VideoView> {
  final VideoStore _videoStore = getIt<VideoStore>();
  final CollectionStore _collectionStore = getIt<CollectionStore>();
  final AuthStore _authStore = getIt<AuthStore>();

  VideoPlayerController? _controller;
  bool _isInitialized = false;

  @override
  void initState() {
    super.initState();
    _initializeVideo();
  }

  Future<void> _initializeVideo() async {
    if (_videoStore.currentVideo != null) {
      _controller = VideoPlayerController.asset(
        _videoStore.currentVideo!.videoUrl,
      );

      await _controller!.initialize();
      await _controller!.setLooping(true);
      await _controller!.play();

      if (mounted) {
        setState(() {
          _isInitialized = true;
        });
      }
    }
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Observer(
        builder: (_) {
          final video = _videoStore.currentVideo;

          if (video == null) {
            return const Center(child: CircularProgressIndicator());
          }

          return Stack(
            children: [
              // 视频背景
              _buildVideoBackground(video),

              // 内容层
              SafeArea(
                top: false,
                bottom: false,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 顶部导航栏
                    _buildAppBar(),

                    const Spacer(),

                    // 视频详情
                    _buildVideoDetails(video),
                  ],
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  // 构建视频背景
  Widget _buildVideoBackground(VideoModel video) {
    if (_isInitialized && _controller != null) {
      return SizedBox.expand(
        child: FittedBox(
          fit: BoxFit.cover,
          child: SizedBox(
            width: _controller!.value.size.width,
            height: _controller!.value.size.height,
            child: VideoPlayer(_controller!),
          ),
        ),
      );
    } else {
      // 加载中或出错时显示缩略图
      return Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(video.thumbnailUrl),
            fit: BoxFit.cover,
          ),
        ),
      );
    }
  }

  // 构建顶部导航栏（添加蒙层）
  Widget _buildAppBar() {
    return Container(
      padding: EdgeInsets.only(
        top: 56.h,
        bottom: 10.h,
        left: 20.w,
        right: 20.w,
      ),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [Colors.black.withAlpha(178), Colors.transparent],
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => GoRouter.of(context).pop(),
            child: Icon(MyIcons.iconBack, color: Colors.white, size: 24.sp),
          ),

          // 标题
          Text(
            'Video',
            style: TextStyle(
              color: Colors.white,
              fontSize: 22.sp,
              fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
              fontWeight: FontWeight.w400,
            ),
          ),

          // 举报按钮
          GestureDetector(
            onTap: () async {
              final video = _videoStore.currentVideo;
              if (video == null) return;
              await ReportDialog.show(
                context,
                title: 'Report',
                description: 'Please select a reason for reporting this video.',
                onSubmit: (type) async {
                  // block 也算举报成功
                  MyToast.showSuccess(context, 'Report successful');
                  await getIt<VideoService>().deleteVideo(video.id);
                  await _videoStore.loadVideos();
                  GoRouter.of(context).pop();
                },
              );
            },
            child: Icon(MyIcons.iconReport, color: Colors.white, size: 28.sp),
          ),
        ],
      ),
    );
  }

  // 构建视频详情
  Widget _buildVideoDetails(VideoModel video) {
    return Container(
      width: 1.sw,
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [Colors.transparent, Colors.black.withAlpha(178)],
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 视频标题
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 标题和描述
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      video.title,
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20.sp,
                        fontWeight: FontWeight.bold,
                        fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                      ),
                    ),
                    SizedBox(height: 8.h),
                    Text(
                      video.description,
                      style: TextStyle(
                        color: Colors.white.withAlpha(204),
                        fontSize: 14.sp,
                        fontFamily: GoogleFonts.inter().fontFamily,
                      ),
                      maxLines: 3,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                ),
              ),

              SizedBox(width: 16.w),

              // 收藏按钮
              Observer(
                builder: (_) {
                  final isCollected = _collectionStore.isVideoInCollection(
                    video.id,
                  );

                  return GestureDetector(
                    onTap: () => _toggleCollection(video.id),
                    child: Container(
                      width: 40.w,
                      height: 40.w,
                      decoration: BoxDecoration(
                        color: Colors.black.withAlpha(76),
                        shape: BoxShape.circle,
                        border: Border.all(
                          color: Colors.white.withAlpha(76),
                          width: 1.w,
                        ),
                      ),
                      child: Icon(
                        isCollected
                            ? MyIcons.iconCollectFill
                            : MyIcons.iconCollect,
                        color: isCollected ? MyColors.blue : Colors.white,
                        size: 24.sp,
                      ),
                    ),
                  );
                },
              ),
            ],
          ),

          SizedBox(height: 40.h),
        ],
      ),
    );
  }

  // 切换收藏状态
  Future<void> _toggleCollection(String videoId) async {
    // 检查用户是否已登录
    if (_authStore.currentUser == null) {
      // 用户未登录，显示登录提示对话框
      await LoginDialog.show(
        context,
        title: 'Login Required',
        description: 'You need to login to collect this video.',
        returnPath: GoRouterState.of(context).matchedLocation,
      );
      return;
    }

    try {
      setState(() {});
      // 切换收藏状态
      await _collectionStore.toggleVideoCollection(videoId);
    } catch (e) {
      // 显示错误提示
      if (mounted) {
        MyToast.showError(context, 'Failed to toggle collection: $e');
      }
    }
  }
}
